<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="180"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出') && supplierExportConfig.supplier"
            size="mini"
            type="primary"
            icon="el-icon-download"
            :loading="exportLoading"
            @click="handleExport"
            >导出</el-button
          >
          <el-button
            v-if="showBtn('新增')"
            size="mini"
            type="primary"
            @click="handleAddFreight"
            >新增</el-button
          >
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import BasicTableForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import {
  queryFreightListService,
  editFreightService,
  exportFreightListService,
  switchStatusService
} from '@api/supplier/management/freight';
import { queryManageAreaService } from '@api/supplier/components';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import { createExcelByExport } from '@/utils/bizUtils';
import { getTableAction } from '@/utils/getBtnsRender'

export default {
  mixins: [ BasicPage ], // 分页数据及方法 表单基础方法
  components: {
    BasicTableForm,
    BasicTable
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  data () {
    return {
      showSearchForm: false,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      formData: {
        supplierCode: '', // 供应商代码
        supplierName: '', // 供应商名称
        createUser: '', // 创建人
        createDept: '', // 创建人所属部门
        createDate: '', // 创建时间
        startTime: '', // 创建开始时间
        endTime: '', // 创建开始时间
        enabled: '', // 运费状态
        status: '', // 审批状态
      },
    };
  },
  created () {
    this.getTableData();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '查看', method: this.handleView },
        { label: '编辑', method: this.handleAddFreight, hasAuth: true },
        { label: `${row.enabled ? '停用' : '启用'}`, authLabel: '停用', method: this.switchStatusConfirm, hasAuth: true },
        { label: '审批日志', method: this.handleViewLog },
      ]
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 创建日期赋值
    formatCreateDate () {
      const { createDate } = this.formData;
      this.formData.startTime = createDate ? createDate[0] : '';
      this.formData.endTime = createDate ? createDate[1] : '';
    },
    // 获取表格数据
    getTableData () {
      this.formatCreateDate()
      let data = {
        ...this.formData,
        ...this.pagination
      };
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      this.tableInfo.loading = true;
      queryFreightListService(data).then((res) => {
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { records, total } = res.result;
          this.tableInfo.list = records;
          this.pagination.total = total;
        }
      }).catch(() => {
        this.tableInfo.loading = false;
      });
    },
    // 获取采购归属
    async getProcurementBelongData () {
      const { result } = await editFreightService({ dictId: 233 })
      result.forEach(item => {
        item.label = item.itemValue
        item.value = item.id
      });
      return result;
    },
    // 获取采购归属
    async getManageAreaData () {
      const { result } = await queryManageAreaService()
      result.forEach(item => {
        item.label = item.manageAreaName
        item.value = item.manageAreaId
      });
      return result;
    },
    // 提交
    handleView (row) {
      this.$router.push({ name: 'viewFreightDetail', query: { supplierId: row.supplierId } })
    },
    // 新增
    handleAddFreight (row) {
      if (row.id) {
        this.queryDataPermissionAction(row.supplierId).then(res => {
          if (res) {
            this.$router.push({ name: 'addFreight', query: { supplierId: row.supplierId } })
          }
        })
      } else {
        this.$router.push({ name: 'addFreight' })
      }
    },
    switchStatusConfirm (row) {
      this.$confirm(`确定要${row.enabled ? '停用' : '启用'}此条信息吗？`, '提示', {
        type: 'warning',
      }).then(() => {
        this.handleSwitchState(row)
      }).catch(() => {});
    },
    // 停启用
    handleSwitchState (row) {
      const { enabled, supplierId, id } = row
      let status = null;
      if (enabled == 0) {
        status = 1
      }
      if (enabled == 1) {
        status = 0
      }
      switchStatusService({ status, supplierId, id }).then((res) => {
        if (isResponseSuccess(res)) {
          this.$message.success('操作成功')
        }
        this.getTableData()
      })
    },
    // 查看日志
    handleViewLog (row) {
      this.$router.push({ name: 'auditLog', query: { supplierId: row.supplierId, module: 1 } })
    },
    // 导出
    handleExport () {
      this.formatCreateDate()
      this.exportLoading = true;
      exportFreightListService({ ...this.formData, size: 1000 }).then(res => {
        this.exportLoading = false;
        createExcelByExport({ excelTitle: '运费管理信息', res })
      })
    }
  }
};
</script>
